<template>
<div class="totalStyle approval">

    <div class="tablestyle">
      <div class="titleStyle">
        <p   class="leftTitle font_w">审批流程</p>
        <el-select v-model="modeldata.companyId" placeholder="Select" style="width: 240px" @change="WorkTemplateListFun">
            <el-option
                v-for="item in modeldata.dropdown.companyList"
                :key="item.id"
                :label="item.companyName"
                :value="item.id"
                
            />
            </el-select>
      </div>
      <div class="bottomBox flex">
          <div class="leftBox">
              <p class="text-Style">审批模板</p>
                <div class="treeBox mt-16">
                    <el-tree :data="modeldata.WorkTemplateList" 
                            node-key="templateId"
                            default-expand-all = 'true'
                            :props="{ children: 'workTemplate',label: 'templateName',level:'level'}"
                            highlight-current = 'true'
                            @node-click="handleNodeClick" >
                             <template  v-slot:default="{ node, data }">
                              <div @click="showTreeData(data)" >
                                <span v-if="data.templateId != modeldata.treeData.operationVis" class="custom-tree-node" :class="{'activeStyle': data.templateId === modeldata.templateId }">
                                    <span v-if = 'node.level == 2' style="display: inline-block;" >{{ node.label }}&nbsp;&nbsp;{{data.version}}</span>
                                    <span v-else style="display: inline-block;">{{ node.label }}</span>
                                    <span v-if = 'node.level !== 2'>
                                        <el-dropdown>
                                          <span class="el-dropdown-link">
                                           <el-icon ><MoreFilled /></el-icon>
                                          </span>
                                          <template #dropdown >
                                            <el-dropdown-menu>
                                              <el-dropdown-item command="b" v-if = 'node.level !== 2' @click="addTreeNode(data)">添加模板</el-dropdown-item>
                                              <!-- <el-dropdown-item command="d" v-if = 'node.level == 2' @click="delTreeNode(data.templateId)">删除</el-dropdown-item> -->
                                            </el-dropdown-menu>
                                          </template>
                                        </el-dropdown>
                                    </span>
                                </span>
                                <span v-else class="custom-tree-node">
                                    <input
                                        style="width: 50%"
                                        size="mini"
                                        ref="inputVal"
                                        :value="node.label"
                                        placeholder="请输入分类名"
                                        @change="nameChange(node,data,$event)"
                                    />
                                    <span> 
                                    </span>
                                  </span>
                              </div>
                          </template>
                  </el-tree>
                </div>
          </div>
          <div class="rightBox"  v-if="modeldata.showPage"> 
                    <div class="chartstyle">
                        <!-- <div>
                            <el-empty>
                                <el-button @click="setApproval" type="primary">设置</el-button>
                            </el-empty>
                        </div> -->
                        <div class="approvalBox border-right">
                        <p class="text-Style">审批</p>
                        <template  v-for="(aproval,index) in modeldata.tableData" :key="index">
                            <div class="cardBox">
                                <div  class="topBox between">
                                <div>
                                    <input ref='textref' 
                                            class="textref"
                                                v-if="aproval.showInput"
                                                style="width: 50%"
                                                :value="aproval.dutyName"
                                                name = 'text'
                                                placeholder="请输入审批名称"
                                                @blur.stop="saveText(index,$event)"
                                                autofocus="autofocus"
                                            />
                                    <span v-else  class="dutyname-size"  v-on:dblclick="updateText($event)">{{aproval.dutyName}}  </span>
                                        <el-icon @click="showInput(aproval,index)" class="edit_icon cursor" ><Edit /></el-icon>
                                </div>
                                    <el-icon v-if="index>0" style="color:#A9AFB9" class="m-2 cursor" @click="deleteTemplate(index)"><Close /></el-icon>
                                </div>
                                <div  class="bottomContent">
                                    <el-select v-model="aproval.userId" class="m-2" :disabled = '!modeldata.isEdit' placeholder="请选择人员" @change="getname" @click="modeldata.userIndex = index">
                                        <el-option
                                        v-for="item in modeldata.dropdown.userList"
                                        :key="item.id"
                                        :label="item.realName"
                                        :value="item.id+''"
                                        :disabled = '!modeldata.isEdit'
                                        />
                                    </el-select>
                                </div>
                            </div>
                            <span v-if="index !== modeldata.tableData.length-1" :size = '30' class=" addApproval"><el-icon><Bottom /></el-icon></span>
                        </template>
                            <el-button v-if="modeldata.isEdit" @click="addApproval" class="addApproval mt-16 cursor" type="primary">增加</el-button>
                        </div>
                        <div class="approvalBox">
                            <p class="text-Style ml-16">抄送</p>
                            <template  v-for="(copy,index) in modeldata.copyUsers" :key="index">
                                <div class="cardBox">
                                    <div  class="topBox between">
                                        <span class="dutyname-size" >抄送人</span>
                                    </div>
                                    <div  class="bottomContent">
                                        <el-select multiple v-model="copy.userId" class="m-2" placeholder="请选择人员" :disabled = '!modeldata.isEdit'>
                                            <el-option
                                            v-for="item in modeldata.dropdown.userList"
                                            :key="item.id"
                                            :label="item.realName"
                                            :disabled = '!modeldata.isEdit'
                                            :value="item.id+''"
                                            />
                                        </el-select>
                                    </div>
                                </div>
                            </template>
                        </div>  
                    </div>
                    <div class="submitBox" v-if="modeldata.isEdit" >
                            <el-button type="primary" @click="saveApproval">确定</el-button>
                    </div>
          </div>
          <div class="rightBox" v-else>
              <el-empty description="暂无模板故据，请选择节点添加模板" />
          </div>
            
      </div>
</div>
</div>

</template>
<script setup>
import { onBeforeMount, watch, getCurrentInstance } from "vue";
import { reactive, ref, markRaw} from "vue";
import { ElMessage, ElMessageBox,ElNotification } from "element-plus";
import { Warning,Close,Bottom,Edit } from "@element-plus/icons-vue";
import store from '@/store'
import { getUserList as getUserList,getWorkTemplate as getWorkTemplate, deleteWorkTemplate as deleteWorkTemplate, 
operateWorkTemplate as operateWorkTemplate, getCompanyList as getCompanyList, getJobAllUsers as getJobAllUsers } from '@/api/user.js'
const editDataRef = ref('');
const addform = ref('')
const popoverRef = ref()
const textref = ref()
const inputVal = ref()
let modeldata =  reactive({
    showPage:false,
    isEdit:false,
    userIndex:'',
    companyId:'',
    WorkTemplateList:[],
    templateTitle:'',
    templateType:'',
    templateId:'',
    treeData:{
      operationVis:''
    },
    editNode:'',
    dropdown:{
      userList:[{}],
      companyList:[]
    },
    approvalData:{
        showApproval:false,
        showSaveButton:false,
    },
    tableData:[{
      dutyName:'审批人',
      userId:'',
      showInput:false
    }],
    copyUsers:[{
      dutyName:'',
      userId:''
    }]
})
const getUserListFun = (id) => {
  getUserList(id).then((res)=>{
    if(res.code === 200){
        modeldata.dropdown.userList = res.body;
    }else{
        ElNotification({
              title: '警告',
              message: res.message?res.message:'服务器异常',
              type: 'warning',
            })
            if(res.code === 100007 ||  res.code === 100008){
                    store.dispatch('app/logout')
                }
    }
  })
}
const getWorkTemplateFun = (id) => {
  getWorkTemplate(id).then((res) => {
        if(res.code === 200){
        modeldata.WorkTemplateList = res.body;
        // modeldata.templateId = modeldata.WorkTemplateList[0].workTemplate[0].templateId
        // if(!modeldata.templateId){
            showTreeData(modeldata.WorkTemplateList[0].workTemplate[0])
        // }
        
    }else{
        ElNotification({
              title: '警告',
              message: res.message?res.message:'服务器异常',
              type: 'warning',
            })
            if(res.code === 100007 ||  res.code === 100008){
                    store.dispatch('app/logout')
                }
    }
  })
}
const getJobAllDeptFun = ()=>{
    getCompanyList().then((res)=>{
            if(res.code === 200){
                modeldata.dropdown.companyList = res.body;
                modeldata.companyId = modeldata.dropdown.companyList[0].id
                getWorkTemplateFun(modeldata.companyId)
                getUserListFun(modeldata.companyId)
            }else{
                ElNotification({
                    title: '警告',
                    message: res.message?res.message:'服务器异常',
                    type: 'warning',
                    })
                    if(res.code === 100007 ||  res.code === 100008){
                            store.dispatch('app/logout')
                        }
            }
    })

}
onBeforeMount(()=>{
  getJobAllDeptFun()
//   getUserListFun()
})
/**
 * 显示部门数据
 */
const showTreeData = (data)=>{
  console.log(data);
  if(data&&data.level === 2){  //审批模板回填数据
    modeldata.showPage = true
      modeldata.templateType = data.templateType;
      modeldata.templateId = data.templateId;
      modeldata.tableData = data.dutyNames&&data.dutyNames.length>0?data.dutyNames:[{
        dutyName:'审批人',
        userId:'',
        userName:''
      }]
       let copy_data = []
       if(data.copyUsers&&data.copyUsers.length>0){
         data.copyUsers.forEach((item) =>{
            copy_data.push(item.userId)
        })
       }
      modeldata.copyUsers = [{
        dutyName:'',
        userId:copy_data
      }]
      //判断是否需要确定按钮（当没有数据时，默认是新的，可以编辑）
      
      if(modeldata.tableData&&modeldata.tableData.length == 1&& modeldata.tableData[0].userId == ''&& modeldata.copyUsers&&modeldata.copyUsers.length == 1&&modeldata.copyUsers[0].userId.length == 0){
          modeldata.isEdit = true
      }else{
           modeldata.isEdit = false
      }
      console.log(modeldata.isEdit)
  }
  //   modeldata.table.equipmentName = data.equipmentName;
  //   modeldata.table.equipmentParentId = data.id;
  //  queryTableData(data.id)
}
//点击模板获取数据
const getTemplate = (item) => {
    modeldata.tableData = item.dutyNames
    modeldata.templateTitle = item.templateName
    modeldata.templateId = item.templateId
    modeldata.approvalData.showApproval = modeldata.tableData&&modeldata.tableData.length>0?true: false;
}
//切换部门获取模板列表
const WorkTemplateListFun = (val) => {
        modeldata.showPage= false
      getWorkTemplateFun(val)
      getUserListFun(val)
}
//设置
const setApproval = () => {
    if(modeldata.templateId){
        modeldata.approvalData.showApproval = true
    }
}
//删除审批节点
const deleteTemplate = (index) => {
  modeldata.tableData.splice(index,1)
}
//修改审批名称
// const editText = (data,index)=>{
//   // modeldata.tableData[index].showInput = true;
//   // console.log(textref.value)
//   textref.value.autofocus = true;
// }

//修改审批节点名称
const updateText = (event) => {
  console.log(event)
  event.target.contentEditable = true;
  // 设置焦点到span标签
  event.target.focus();
}
//获取人员
const getname = (val) => {
  let index = modeldata.dropdown.userList.findIndex((item)=>{return item.id == val});
  if(index>-1){
    modeldata.tableData[modeldata.userIndex].userName = modeldata.dropdown.userList[index].realName;
  }
}
//审批节点名称失去焦点
const saveText = (index,event) =>{
  console.log(event)
  if(event.target.value){
    modeldata.tableData[index].showInput = false;
    modeldata.tableData[index].dutyName = event.target.value
  }else{
    ElNotification({
              title: '警告',
              message: '请输入审批名称',
              type: 'warning',
            })
  }
  
  // 将用户编辑后的文本保存到text中
  // aproval.dutyName = event.target.innerText;
  // 让span标签变回不可编辑状态
  // event.target.contentEditable = false;
  // console.log(textref.value)
  // modeldata.tableData[index].dutyName = aproval;
  // modeldata.tableData[index].showInput = true;
}
//点击编辑图标
const showInput = (aproval,index)=>{
  modeldata.tableData[index].showInput = true;
  // textref.value.focus();
  setTimeout(() => {
    let textref = document.querySelectorAll('input[name="text"]')
    textref[0].focus()
  })
  // let textref = document.querySelectorAll('input')
  // console.log(textref)
}
//添加审批流
const addApproval = ()=>{
  let obj = {
    dutyName:'审批名称',
    userId:'',
    userName:''
  }
  modeldata.tableData.push(obj)
}
//保存模板内容
const operateCompanyFun = (obj) => {
  operateWorkTemplate(obj).then((res) => {
      if(res.code === 200){
        checkCancel()
        modeldata.isEdit = false
            ElMessage({
              showClose: true,
              message: '审批模板保存成功',
              type: 'success',
            })
    }else{
        ElNotification({
              title: '警告',
              message: res.message?res.message:'服务器异常',
              type: 'warning',
            })
            if(res.code === 100007 ||  res.code === 100008){
                    store.dispatch('app/logout')
                }
    }
    })
}
//添加模板
const addTreeNode = (data)=>{
  let obj = {
      "templateName": data.templateType,
      "templateType": data.templateType,
      companyId:modeldata.companyId
  }
   operateCompanyFun(obj)
}

//删除模板
const delTreeNode = (id) => {
    deleteWorkTemplate(id).then((res) => {
      if(res.code === 200){
            getWorkTemplateFun(modeldata.companyId)
        }else{
            ElNotification({
                  title: '警告',
                  message: res.message?res.message:'服务器异常',
                  type: 'warning',
                })
                if(res.code === 100007 ||  res.code === 100008){
                        store.dispatch('app/logout')
                    }
        }
        })
}
/**
 * 编辑树节点
 */
// const editTree = (node,data)=>{
//   modeldata.treeData.operationVis = data.templateId;
// }
//编辑结束
// const nameChange = (node,data,e)=>{
//   data.templateName = e.target.value;
//   //部门名称为空时，不能添加或者编辑
//   if(data && !data.templateName){
//     ElMessage('分类名称不能为空.')
//     checkCancel()
//     return false
//   }
//   //编辑时调用的接口
//   if(data){
//     let obj = {
//           templateId:data.templateId,
//           templateName : data.templateName,
//           templateType:data.templateType
//     }
//     operateCompanyFun(obj)
    
//   }
// }
const checkCancel = ()=>{
  modeldata.treeData.operationVis = '',
    getWorkTemplateFun(modeldata.companyId)
}

//保存审批流
const saveApproval = () => {
  console.log(modeldata.copyUsers)
  let arr = [];
  modeldata.copyUsers[0].userId.forEach((item)=>{
    let item_obj = {};
    item_obj.userId = item;
    arr.push(item_obj);
  })
  let obj = {
    dutyNames:modeldata.tableData,
    copyUsers:arr,
    templateType:modeldata.templateType,
    templateId: modeldata.templateId,
    companyId:modeldata.companyId
  }
  operateCompanyFun(obj)
}

</script>
<style  lang = 'less' scoped>
.approval{
    .dutyname-size{
      font-size: 14px;
      color: #1C222C;
    }
    .submitBox{
      background-color: #F2F5FA;
      padding: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top:16px ;
    }
    .border-right{
      border-right: 1px solid #DADFE6;
    }
    :deep(.el-tree-node__label){
      width: 100%;
    }
    .custom-tree-node{
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
  }
    :deep(.el-table--fit){
      height:100%;
    }
    :deep(.el-table__body-wrapper) {
      overflow-y: auto;
    }
    .tablestyle {
      position: relative;
      :deep(.el-table__header thead tr) {
        background-color: rgba(64, 158, 255, 0.1);
      }
      :deep(.el-col-3 ){
        max-width: none;
      }
    }

    .demo-pagination-block {
      margin-top: 16px;
      position: absolute;
      bottom: 32px;
      right: 32px;
    }
    .dialogBox{
          :deep(.el-form--inline .el-form-item){
              width: 100%;
          }
          :deep(.el-input){
                width: 100%;
            }
          :deep(.el-select){
            width: 100%;
          }
          :deep(.el-dialog__body){
            padding-right: 160px;
          }
          :deep(.el-form-item--default .el-form-item__content){
            width: calc(100% - 80px);
        }
          :deep(.el-dialog__header) {
            border-bottom: 1px solid #cccccc;
            padding: 16px;
            margin-right: 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
          }
          :deep(.el-dialog__title) {
            color: #1C222C;
            font-size: 20px;
            width: 100px;
          }
          :deep(.el-dialog__headerbtn ){
            position: static;
            top: 0px;
            right: 0;
            padding: 0;
            width: auto;
            height: auto;
          }
    }

    .totalStyle{
        height: 100%;
    }
    .bottomBox{
      width: 100%;
      padding: 0;
    }
    .rightBox{
      width: 75%;
      padding: 16px;
      .chartstyle {
        height: calc(100% - 100px);
        display: flex;
      }
    }
    .leftBox{
      width: 25%;
      padding: 16px;
      border-right: 1px solid #DADFE6;
      height: 100%;
      overflow-y: auto;
      .addPart{
        width: 100%;
      }
    }
    .partTitle{
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .cardBox{
        width: 60%;
        height: 80px;
        background-color: #EDF0F5;
        border-radius: 8px;
        padding: 8px;
        margin: 0 auto;
        .topBox{
            height: 30px;
        }
        :deep(.el-select){
            width: 100%;
        }
        :deep(.el-input){
            width: 100%;
        }

    }
    .approvalBox{
        display: flex;
        flex-direction: column;
        height: 100%;
        overflow-y: auto;
        width: 50%;
    }
    .addApproval{
        width: 30%;
        margin: 0 auto;
        text-align: center;
    }
    .edit_icon{
        margin-left: 8px;
        margin-top: 2px;
    }
    .text-Style{
      color: #1C222C;
      font-size: 16px;
      font-weight: 700;
    }
}
.activeStyle{
    background-color: #EcF5FF;
}
</style>